﻿using DoorlockManage;
using System.Text;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Runtime.ConstrainedExecution;
using System.Threading;
using System.Windows.Forms;

namespace HlELock
{
    internal class Program
    {
        static IntPtr m_hHID = new IntPtr(-1);//设备句柄
        public const uint GENERIC_READ = 0x80000000;//winapi函数CreateFile相关参数
        public const uint GENERIC_WRITE = 0x40000000;
        public const uint FILE_SHARE_READ = 0x00000001;
        public const uint FILE_SHARE_WRITE = 0x00000002;
        public const uint OPEN_EXISTING = 3;
        public const uint FILE_FLAG_OVERLAPPED = 0x40000000;
        public const int DBT_DEVICEARRIVAL = 0x8000;  // 检测到新设备
        public const int DBT_DEVICEREMOVEPENDING = 0x8003; // 设备将要移除
        public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;  // 设备已经移除
        public const int DBT_DEVTYP_DEVICEINTERFACE = 0x00000005; // device interface class
        public const int DEVICE_NOTIFY_WINDOW_HANDLE = 0x00000000;
        public const int ERROR_NO_MORE_ITEMS = 259;
        public const uint DEVICE_ARRIVAL = 3;	// 设备插入事件,已经插入
        public const uint DEVICE_REMOVE_PEND = 1;	// 设备将要拔出
        public const uint DEVICE_REMOVE = 0;	// 设备拔出事件,已经拔出
        static void Main(string[] args)
        {
            InitSelDev();
            OpenDevice();

            Thread s1 = new Thread(ReceiveMessage);
            s1.IsBackground = true;
            s1.Start();

            Thread s = new Thread(SendMessage);//新建线程
            s.IsBackground = true;
            s.Start();


            Console.WriteLine("运行完成");
            Console.ReadKey();
        }
        public static void InitSelDev()//检测设备
        {
            uint deviceNo = 0;
            byte[] buf = new byte[1024];
            IntPtr hHID = IntPtr.Zero;//设备句柄
            int strlen = 0;
            string strpath = "";//设备路径

            winapi.SetLastError(0);
            var list = new List<string>();
            while (winapi.GetLastError() != ERROR_NO_MORE_ITEMS)
            {
                if (CH9326DLL.CH9326GetDevicePath(deviceNo, buf, Convert.ToUInt32(buf.Length)))
                {
                    //打开设备,并获得设备句柄
                    hHID = winapi.CreateFile(buf, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);
                    if (hHID == new IntPtr(-1))
                    {
                        deviceNo++;
                        continue;
                    }
                    for (int i = 0; i < buf.Length; i++)
                    {
                        if (buf[i] == 0)
                        {
                            strlen = i + 1;//DevicePath路径长度
                            break;
                        }
                    }
                    strpath = Encoding.Default.GetString(buf, 0, strlen - 1);//得到设备路径
                    list.Add(strpath);
                    Console.WriteLine(strpath);
                    winapi.CloseHandle(hHID);
                }
                deviceNo++;
            }
        }

        public static void CloseDevice()
        {
            if (m_hHID != new IntPtr(-1))
            {
                CH9326DLL.CH9326CloseDevice(m_hHID);
            }
        }
        public static void OpenDevice()
        {
            UInt16 VID = 0, PID = 0, VER = 0;//VID、PID和版本号
            m_hHID = CH9326DLL.CH9326OpenDevicePath("\\\\?\\HID#VID_1A86&PID_E010#6&11a75b18&1&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}");
            if (m_hHID == new IntPtr(-1))
            {
                Console.WriteLine("打开设备失败");
            }

            //获取厂商ID和设备ID
            if (CH9326DLL.CH9326GetAttributes(m_hHID, ref VID, ref PID, ref VER) == 0)
            {
                CH9326DLL.CH9326CloseDevice(m_hHID);
                return;
            }
            Console.WriteLine(string.Format("设备已连接,VID={0:X} PID={1:X} VER={2:X} ", VID, PID, VER));
            UInt16 inportlen = 0, outportlen = 0;
            CH9326DLL.CH9326GetBufferLen(m_hHID, ref inportlen, ref outportlen);
            CH9326DLL.CH9326SetTimeOut(m_hHID, 3000, 3000);

        }
        public static void SendMessage()//发送数据
        {

            byte[] OutputReport = new byte[64];
            IntPtr hEventObject = new IntPtr(0);
            byte[] data;


            Array.Clear(OutputReport, 0, OutputReport.Length);
            byte[] d = { 0x58, 0x4b, 0x50, 0x4b, 0x04, 0x09 };
            d[5] = 0x04;
            byte len = (byte)d.Length;
            Array.Copy(d, OutputReport, d.Length);
            if (CH9326DLL.CH9326WriteData(m_hHID, OutputReport, len, hEventObject) == 0) //发送数据
            {
                Console.WriteLine("发送数据失败");
            }
            winapi.CloseHandle(hEventObject);
            return;
        }


        public static void ReceiveMessage()
        {
            byte[] recvDataBuf = new byte[1024];
            uint len;//接受缓冲区大小  
            string strbuf, st;

            if (m_hHID == new IntPtr(-1))
            {
                MessageBox.Show("设备尚未连接");
                return;
            }
            if (CH9326DLL.CH9326InitThreadData(m_hHID) == 0)
            {
                Console.WriteLine("CH9326InitThreadData Error");
                return;
            }
            uint m_uRecvED = 0;//接收数据大小
            len = Convert.ToUInt32(recvDataBuf.Length);
            while (true)//取数据
            {
                var read = CH9326DLL.CH9326ReadThreadData(m_hHID, recvDataBuf, ref len);

                strbuf = "";
                if (len != 0)
                {
                    for (uint i = 0; i < len; i++)
                    {
                        strbuf = strbuf + recvDataBuf[i].ToString("X2") + " ";//以2位16进制输出，加空格
                    }
                    Console.WriteLine("_AppendText_" + strbuf);
                    m_uRecvED += len;//已接收数据大小
                    st = "已接收数据:" + m_uRecvED.ToString("d");
                    Console.WriteLine("st_" + st);
                }
                Thread.Sleep(10);
            }

            CH9326DLL.CH9326StopThread(m_hHID);
        }


    }


}